# -*- coding: utf-8 -*-
# @file    : patch
# @Date    : 2020/11/26
# @Author  :
# @Version : 1.0.0
"""
Web Resource Patcher
"""
from .constant import POE_HOST, CDN_HOST
from ._misc import report_process_time
from .log import logger as _logger
from .config import config

user_config = config['user']


@report_process_time
def index_html_patch(content):
    _logger.info("执行资源补丁: 替换远程资源的地址为本机地址")
    # 替换资源的地址
    content = content.replace(b'https://poecdn.game.qq.com/js', b'/js')
    content = content.replace(b'https://poecdn.game.qq.com/image', b'/image')
    content = content.replace(b'https://poecdn.game.qq.com/font', b'/font')
    content = content.replace(b'https://poecdn.game.qq.com/css', b'/css')
    # 移除不兼容的代码
    _logger.info("执行资源补丁: 移除不兼容的代码")
    content = content.replace(b'document.domain="qq.com";', b'')
    # 移除实时搜索要求登录
    _logger.info("执行资源补丁: 移除实时搜索需要登录的限制")
    content = content.replace(b'loggedIn &&', b'')
    return content


@report_process_time
def icon_host_patch(content, host):
    """
    更换fetch接口中的物品图标的主机为本服务
    从而可以经过image_loader进行图片缓存， 减少对腾讯官方服务的请求
    :param content:
    :param host
    :return:
    """
    _logger.info("执行资源补丁: 替换fetch接口中图片资源的远程地址为本机地址")
    content = content.replace(b'https:\\/\\/' + POE_HOST.encode(), b'http://' + host.encode())
    content = content.replace(b'https:\\/\\/' + CDN_HOST.encode(), b'http://' + host.encode())
    return content


@report_process_time
def trade_js_patch(content):
    # 替换实时搜索连接的 websocket 地址为 本地的5005端口
    _logger.info("执行资源补丁:  替换实时搜索连接的 websocket 地址为 本机的5005端口")
    content = content.replace(b'"wss://"+location.host',
                              b'"ws://"+location.hostname+":%d"' % user_config['live_search_port'])
    return content
